﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;

namespace TaxiDispatchClient
{
    public partial class PhoneUserAreaStatisticsForm : DevExpress.XtraEditors.XtraForm
    {
        public PhoneUserAreaStatisticsForm(int type)
        {
            InitializeComponent();
            _type = type;
        }

        private int _type;
        private Thread _thread;

        private void btn_begin_Click(object sender, EventArgs e)
        {
             
            progressBarControl.Position = 0;
            progressBarControl.Visible = true;
            btn_cancel.Visible = true;
            btn_mixForm.Visible = true;
            label_progress.Visible = true;
            label_notice.Visible = true;
            label_progress.Text = "完成： 0%";
            btn_begin.Visible = false;

            
            _thread = new Thread(GetResult);
            _thread.IsBackground = true;
            _thread.Start();

           
        }

        private void GetResult()
        {
            try
            {
                DataSet ds = null;
                switch (_type)
                {
                    case 0://手机用户
                        ds = MainForm.PositionService.PhoneUserGetList("");
                        break;
                    case 1://私家车用户
                        ds = MainForm.PositionService.PrivateGetPhoneNumberList("");
                        break;
                }
            
                
                if (ds==null || ds.Tables.Count==0)
                {
                    XtraMessageBox.Show("服务器查询错误！");
                    return;
                }
                if (ds.Tables[0].Rows.Count==0)
                {
                    XtraMessageBox.Show("暂无用户！");
                    return;
                }
                BeginInvoke(new MethodInvoker(() =>
                    {
                        progressBarControl.Properties.Minimum = 0;
                        progressBarControl.Properties.Maximum = ds.Tables[0].Rows.Count;
                        chartControl1.Series.Clear();
                        //progressBarControl.Position = 0;
                        //progressBarControl.Visible = true;
                        //btn_cancel.Visible = true;
                        //label_progress.Visible = true;
                        //label_notice.Visible = true;
                        //label_progress.Text = "完成： 0%";
                        //btn_begin.Visible = false;
                    }));


                DataTable dtResult = new DataTable();
                dtResult.Columns.Add("Area");
                dtResult.Columns.Add("Count");
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string phoneNumber = row["PhoneNumber"].ToString();
                    string area = MainForm.PositionService.
                        GetUserAreaByPhoneNumber(phoneNumber.Substring(0,7));
                    if (area.Contains(" "))
                    {
                        area = area.Substring(0, area.IndexOf(' '));    
                    }                    
                    DataRow[] areaRow = dtResult.Select("Area='" + area + "'");
                    if (areaRow.Length==0)
                    {
                        DataRow dtRow = dtResult.NewRow();
                        dtRow["Area"] = area;
                        dtRow["Count"] = 1;
                        dtResult.Rows.Add(dtRow);
                    }
                    else
                    {
                        int count = int.Parse(areaRow[0]["Count"].ToString());
                        count++;
                        areaRow[0]["Count"] = count;
                    }
                    BeginInvoke(new MethodInvoker(() =>
                        {
                            progressBarControl.Position++;
                            
                            float persents = (float)progressBarControl.Position
                                /ds.Tables[0].Rows.Count;
                            persents = persents*100;
                            label_progress.Text = "完成： "+persents.ToString("f2")+"%";
                        }));
                }
                BeginInvoke(new MethodInvoker(() =>
                    {
                        progressBarControl.Visible = false;
                        btn_cancel.Visible = false;
                        btn_mixForm.Visible = false;
                        label_progress.Visible = false;
                        label_notice.Visible = false;
                        btn_begin.Visible = true;
                        btn_begin.Text = "重新统计";
                        btn_begin.Enabled = true;
                        gridControl1.DataSource = dtResult;
                    }));

                Series series = new Series("饼图统计", ViewType.Pie3D);
                foreach (DataRow dr in dtResult.Rows)
                {                
                    string strArea = dr["Area"].ToString();
                    int intCount = int.Parse(dr["Count"].ToString());                
                    SeriesPoint seriesPoint = new SeriesPoint(strArea+":"+intCount,
                       // (double)(intCount/ds.Tables[0].Rows.Count));
                      intCount);
                    series.Points.Add(seriesPoint);                
                }
                Invoke(new MethodInvoker(() =>
                    {
                        series.LegendPointOptions.PointView = PointView.Argument;
                        chartControl1.Titles[0].Text = "用户地区统计图";
                        chartControl1.Series.Add(series);
                        if (WindowState == FormWindowState.Minimized)
                        {
                            WindowState = FormWindowState.Normal;
                        }
                        XtraMessageBox.Show("用户地区统计已完成！");
                    }));
                
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("在创建窗口句柄之前"))
                {
                    Common.CommonRoutine.HandlingExceptions(ex,true);
                }
                
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            if (_thread!=null && _thread.IsAlive)
            {
                _thread.Abort();
            }
            btn_cancel.Visible = false;
            btn_mixForm.Visible = false;
            btn_begin.Visible = true;
            progressBarControl.Position = 0;
            progressBarControl.Visible = false;
            btn_begin.Text = "开始统计";
            btn_begin.Enabled = true;
            label_progress.Visible = false;
            label_notice.Visible = false;
        }



        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void btn_mixForm_Click(object sender, EventArgs e)
        {
             this.WindowState = FormWindowState.Minimized;
        }

        private void btn_exportToExcel_MouseClick(object sender, MouseEventArgs e)
        {
            string title = "";
            switch (_type)
            {
                case 0:
                    title = "手机用户按地区统计结果";
                    break;
                case 1:
                    title = "顺风车用户按地区统计结果";
                    break;
            }
            saveFileDialog1.FileName = title;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }
        
    }
}